<?php

/**
 * This is the model class for table "flash".
 *
 * The followings are the available columns in table 'flash':
 * @property string $id
 * @property string $upload_src
 * @property string $upload_time
 * @property string $uid
 * @property string $username
 */
class Image extends Base {
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'image';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('upload_src', 'length', 'max'=>150),
			array('upload_time, uid', 'length', 'max'=>10),
			array('username', 'length', 'max'=>20),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, upload_src, upload_time, uid, username', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'upload_src' => '上传路径',
			'upload_time' => '上传时间',
			'uid' => '上传id',
			'username' => '上传人',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('upload_src',$this->upload_src,true);
		$criteria->compare('upload_time',$this->upload_time,true);
		$criteria->compare('uid',$this->uid,true);
		$criteria->compare('username',$this->username,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Image the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}


    public function upload() {
        //图片，上传参数
        if (!isset(Yii::app()->params['upload']['img'])) {
            $this->addError('upload', '上传参数未配置');
            return false;
        }
        $upload_params = Yii::app()->params['upload']['img'];
        try {
            $file = Yii::app()->file;
            $file->allowSize = $upload_params['size'];   //上传文件大小
            $file->allowExtensions = $upload_params['allowExtensions'];  //上传文件类型
            $file->setDirectory($upload_params['directory']);  //设置文件上传目录
            $file->upload();
        } catch (CException $e) {
            $this->addError('upload', $e->getMessage());
            return false;
        }
        return $file->getNameWithExtension();
    }

    /**
     * 添加资源
     * @param $pid int 相册ID
     * @return mixed 添加是否成功/返货压缩之后的图片路口
     */
    public function imageAdd($pid) {
        $image_sign = $this->upload();
        if ($image_sign === false) {
            return false;
        }
        //将文件从临时目录挪到正式目录
        $upload_src = $this->moveFile($image_sign);
        if ($upload_src === false) {
            return false;
        }
        $ext = pathinfo($upload_src,PATHINFO_EXTENSION);
        //pdf格式的走压缩逻辑
        if (!in_array(strtolower($ext),array('pdf'))) {
            $process_url = $this->imgProcess($upload_src);
            if ($process_url === false) {
                return false;
            }
            $this->thumb_src = $process_url;  //缩略图路径
        }
        $this->title = Yii::app()->file->getOriginName();
        $this->upload_src = $upload_src;   //原始文件路径
        $this->upload_time = time();   //上传时间
        $this->uid = Yii::app()->session['auth']['id']; //上传人
        $this->username = Yii::app()->session['auth']['username'];
        $this->pid = $pid;
        return $this->save();
    }

    /**
     * 根图片标识从上传临时目录找到文件，并移动到正式目录，删除林目录文件
     * @param $sign string 文件唯一标识
     * @param $type string 文件类型
     * @return string 正式目录个和文件名
     */
    public function moveFile($sign) {
        //获取上传目录
        if (isset(Yii::app()->params['upload']['img']['directory'])) {
            $upload_dir = Yii::app()->params['upload']['img']['directory'];
        } else {
            $upload_dir = 'upload';
        }
        $root_path = Yii::getPathOfAlias('webroot');  //程序跟目录
        $upload_file = $root_path . '/' . $upload_dir . '/'. $sign; //上传文件的临时目录
        if (!file_exists($upload_file)) {
            $this->addError('add', '添加失败，图片资源不存在，请重新上传');
            return false;
        }

        //正式目录，以每天为单位，同一天的文件放到同一目录
        $flash_dir = '/static/flash/' . date('Y-m-d');
        if (!is_dir($root_path . $flash_dir)) {
            mkdir($root_path . $flash_dir, 0777, true);
        }
        $ext = pathinfo($sign, PATHINFO_EXTENSION);  //获取文件扩展名
        $new_file_name = date('YmdHis') . uniqid() . ".{$ext}";
        //如果新文件名已经存在，保存失败，让重新上传
        $new_file = $root_path . $flash_dir . '/' . $new_file_name;
        if (file_exists($new_file)) {
            $this->addError('add', '保存失败，请重新上传图片');
            return false;
        }
        //上传文件复制到正式目录，并已时间来命名
        copy($upload_file, $new_file);
        //删除临时目录文件
        unlink($upload_file);
        return $flash_dir . '/' . $new_file_name;
    }
    
    public function batchDelete($id_list) {}

    /**
     * 图片压缩
     * @param $src string 目标图片地址
     * @param $witdh double 压缩后的宽
     * @param $height double 压缩后的高
     * @param $desc string 压缩后的地址
     * @return mixed 压缩成功，返回压缩地址/失败
    */
    public function imgProcess($src) {
        if (empty($src) ) {
            $this->addError('add', '参数非法');
            return false;
        }
        //压缩相关参数
        $params = Yii::app()->params['upload']['imgProcess'];
        if (!isset($params['image']) || !isset($params['directory'])) {
            $this->addError('add', '压缩参数未配置');
            return false;
        }
        $upload_params = $params['image'];
        $root_path = Yii::getPathOfAlias('webroot');
        //压缩相对目录
        $process_dir = '/static/' . $params['directory'] . '/' . date('Y-m-d') . '/';
        $out_dir = $root_path . $process_dir;   //压缩绝对目录
        if (!is_dir($out_dir)) {
            mkdir($out_dir, 0777, true);
        }
        $witdh = $upload_params['width'];
        $height = $upload_params['height'];
        $source = $root_path .  $src;
        try {
            $img_tool = new ImageTool($source, $out_dir);
            //压缩宽度、压缩高度、是否保存
            $process_sign = $img_tool->compressImage($witdh, $height)->getProcessPath();
            return $process_dir  . $process_sign;
        } catch (CException $e) {
            $this->addError('add', $e->getMessage());
            return false;
        }
    }

    /**
     * 删除图片
     * @return bool 删除成功/失败
    */
    public function remove() {
        $root_path = Yii::getPathOfAlias('webroot');  //网站根目录
        $upload_src = $root_path . $this->upload_src;
        $thumb_src = $root_path . $this->thumb_src;

        if (!empty($this->upload_src) && file_exists($upload_src)) {
            $is_success = unlink($upload_src);
            if (!$is_success) {
                $this->addError('remove', '图片文件删除失败');
                return false;
            }
        }
        if (!empty($this->thumb_src) && file_exists($thumb_src)) {
            $is_success = unlink($thumb_src);
            if (!$is_success) {
                $this->addError('remove', '缩略图文件删除失败');
                return false;
            }
        }
        return $this->delete();
    }

    /**
     * 设置分页的查询条件(依赖注入的形式来改变$criteriad对象属性)
     * @param $criteria CDbCriteria $criteriad查询对象
     * @return null
     */
    protected function pageListCondition(CDbCriteria $criteria) {
        if (!empty($this->pid)) {
            $criteria->addCondition('pid=:pid');
            $criteria->params = array(':pid' => $this->pid);
        }
    }

    /**
     * 设置分页的其他操作，排序，分类，等操作(依赖注入的形式来改变$criteriad对象属性)
     * @param $criteria CDbCriteria $criteriad查询对象
     * @return null
     */
    protected function pageListOpt(CDbCriteria $criteria) {
        $criteria->select = 'id,FROM_UNIXTIME(upload_time) as upload_time,upload_src,thumb_src,username,title';
        $criteria->order = 'id desc';
    }

    /**
     * 获取当前图片在相册中上一张、下一张图片id
     * @param $userid string 用户id
     * @return bool|array 上一张、下一张图片id
    */
    public function userImgList($userid) {
        if (empty($this->id) || empty($this->pid) || empty($userid)) {
            $this->addError('range', '图片不存在');
            return false;
        }
        $user = User::model()->findByPk($userid);
        if ($user === null) {
            $this->addError('range', '用户不存在');
            return false;
        }
        $cache_key = 'img_list_'.$userid . $this->pid;
        $user_img_list = Yii::app()->cache->get($cache_key);
        if ($user_img_list === false) {
            $join_table = '(select image_id from user_img where userid=:userid and pid=:pid)';
            $param_val = array(
                ':pid' => $this->pid,
                ':userid' => $userid,
            );
            $data_where = 'a.pid=:pid and b.image_id is null';
            $user_img_list = $this->getDbConnection()->createCommand()
                ->select('a.id,a.upload_src')
                ->from('image a')
                ->leftJoin("$join_table b",'a.id=b.image_id')
                ->where($data_where, $param_val)
                ->queryAll();
            Yii::app()->cache->set($cache_key, $user_img_list, 1800);
        }
        return $user_img_list;
    }
}
